package com.djx.plus.inter;

import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author dingjunxiong
 * @date 2021/10/11 19:32
 */
//@Component
//@Aspect
public class PermissionAspect {


    private final String POINT_CUT = "execution(public * com.crc.das.tenant.modules.**.controller.*.*(..))";

    @Pointcut(POINT_CUT)
    public void pointCut(){}
    /**
     * 处理器处理之前调用
     */
    @Before(value = "pointCut()")
    public boolean before(HttpServletRequest request, HttpServletResponse response,
                          Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Permission permission = findPermissionCheck(handlerMethod);

        //如果没有添加权限注解则直接跳过允许访问
        if (permission == null) {
            return true;
        }
        //获取注解中的值
        String resourceKey = permission.resourceKey();
        //获取当前登录用户资源菜单 权限
        String token = request.getParameter("token");
        //根据当前用户 获取所拥有的菜单资源权限
        List<String> collect = new ArrayList<>();
        //根据权限判断是否 存在跟类上注解的一样 一样则通过
        if (collect.contains(resourceKey)) {
            return true;
        }
        return false;
    }

    /**
     * 根据handlerMethod返回注解信息
     *
     * @param handlerMethod 方法对象
     * @return DasPermission注解
     */
    private Permission findPermissionCheck(HandlerMethod handlerMethod) {
        //在方法上寻找注解
        Permission permission = handlerMethod.getMethodAnnotation(Permission.class);
        return permission;
    }
}
